#include "VPicture.h"
#include "VMain.h"

VPicture::VPicture(void) :
    _texture(INVALID_TEXTURE),
    _loaded(false)
{
}

VPicture::VPicture(const VPicture& another)
{
}

VPicture::VPicture(const std::string& imgpth, int x /*= 0*/, int y /*= 0*/, int w /*= 50*/, int h /*= 50*/)
{
    setGeometry(x, y, w, h);
    loadTexture(imgpth);
}

VPicture::~VPicture(void)
{
    if (_texture != INVALID_TEXTURE)
    {
        VMain::deleteTexture(&_texture);
    }
}

bool VPicture::render() const
{
    if (!VRRWidget::render())
    {
        return false;
    }

    if (!_loaded)
    {
        return false;
    }

    glPushMatrix();


    glTranslatef(_x, _y, 0);
    /* 反N形点
        v        /v
        v      /  v
        v    /    v
        v  /      v
        v/        v
    */

    static const GLfloat texCoords[] =
    {
        0, 0,
        0, 1,
        1, 0,
        1, 1
    };

    GLfloat vertexes[] =
    {
        0,  0,
        0, _h,
        _w, 0,
        _w, _h
    };

    glBindTexture(GL_TEXTURE_2D, _texture);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
    glVertexPointer(2, GL_FLOAT, 0, vertexes);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);

    glPopMatrix();

    return true;
}

bool VPicture::loadTexture(const std::string& imgpth)
{
    if (_texture != INVALID_TEXTURE)
    {
        VMain::deleteTexture(&_texture);
    }

    _loaded = VMain::loadTexture(imgpth, &_texture, NULL, NULL, NULL);

    return _loaded;
}

GLuint VPicture::getTexture(void) const
{
    if (!_loaded)
    {
        return 0;
    }

    return _texture;
}

GLuint VPicture::detach()
{
    GLuint old = _texture;
    _texture = INVALID_TEXTURE;
    _loaded = false;
    return old;
}

void VPicture::attach(GLuint tex)
{
    if (_texture != INVALID_TEXTURE)
    {
        VMain::deleteTexture(&_texture);
    }

    _texture = tex;
    _loaded = true;
}


bool VPicture::isLoaded() const
{
    return this->_loaded;
}

void VPicture::renderAnother(const VPicture& anopic) const
{
    GLuint old = const_cast<VPicture*>(this)->detach();
    const_cast<VPicture*>(this)->attach(anopic.getTexture());
    this->render();
    const_cast<VPicture*>(this)->detach();
    const_cast<VPicture*>(this)->attach(old);
}
